﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WucCloud.Utility.Helper
{
    /// <summary>
    /// Http请求 帮助类
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="strpost">请求参数</param>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public static string PostData(string strpost, string url)
        {
            //表示空字符串，字段为只读
            string json = string.Empty;

            //创建restful请求
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            //请求的方法是post
            request.Method = "POST";
            //请求的内容类型
            request.ContentType = "application/json";

            //得到参数
            string data = strpost;
            //将字节序列存储到数组中，编码方式为UTF-8
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
            //将数组的元素总和给请求的标头
            request.ContentLength = byteData.Length;

            //以流的形式附加参数
            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }

            //执行请求，达到json
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                //以流的形式读取，返回的就是字符串的json格式
                StreamReader reader = new StreamReader(response.GetResponseStream());
                json = reader.ReadToEnd();
            }
            return json;
        }

        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public static string GetData(string url)
        {
            //创建请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            //GET请求
            request.Method = "GET";
            request.ReadWriteTimeout = 5000;
            request.ContentType = "application/json;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();//执行get请求
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("UTF-8"));

            //返回内容JSON
            string retString = myStreamReader.ReadToEnd();
            return retString;
        }
    }
}
